package cn.bas.autoconfigure;

import com.sun.net.httpserver.HttpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.InetSocketAddress;

// 2创建配置类
@Configuration // 配置类
@EnableConfigurationProperties(BasServerProperties.class) // 使用BasServierProperties配置类生效
public class BasServerAutoConfiguration {

    private Logger logger = LoggerFactory.getLogger(BasServerAutoConfiguration.class);

    @Bean
    // @ConditionalOnClass 当类路径下有指定类的条件下 创建HttpServer的Bean
    @ConditionalOnClass(HttpServer.class)
    public HttpServer httpServer(BasServerProperties basServerProperties)throws IOException {
        // 创建HttpServer对象,并启动
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(basServerProperties.getPort()),0);
        httpServer.start();
        logger.info("[httpServer][启动服务器成功，端口{}]",basServerProperties.getPort());
        return httpServer;
    }
}
